package com.lvmama.dashboard.controller;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lvmama.dashboard.core.rop.AjaxMethodHandler;
import com.lvmama.dashboard.core.rop.AjaxRequestContext;
import com.lvmama.dashboard.model.rop.AjaxResponse;

@Controller
@RequestMapping(value="/ajax/router", produces={"application/json;charset=UTF-8"})
public class AjaxRouterController {
	
	@RequestMapping("/rest")
	public @ResponseBody AjaxResponse<? extends Object> rest(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		ServletContext servletContext = request.getSession().getServletContext();
		AjaxRequestContext ajaxRequestContext = (com.lvmama.dashboard.core.rop.AjaxRequestContext) servletContext.getAttribute("ajaxRequestContext");
		AjaxMethodHandler handler  = ajaxRequestContext.getServiceHandler();
		Object obj = handler.getHandlerMethod().invoke(handler.getHandler(), ajaxRequestContext.getRequestData());
		AjaxResponse<?> responseBody = null;
		if(obj instanceof AjaxResponse) {
			responseBody = (AjaxResponse<?>) obj;
		} else {
			responseBody = new AjaxResponse<Object>(AjaxResponse.AJAX_RESPONSE_CODE.ERROR.getCode(), "服务返回无数据", "");
		}
		response.setHeader("Access-Control-Allow-Origin", "*");
		return responseBody;
	}
}
